package com.paradise.ytj.utils;

import android.hardware.Camera;
import android.os.Build;
import android.view.SurfaceHolder;

import java.io.IOException;

/**
 * Created by Administrator on 2017/8/23 0023.
 */

public class CameraUtils {

    private static Camera camera = null;

    /**
     * 初始化相机
     *
     * @return
     */
    public static Camera getCameraInstance() {

        if (camera != null) {
            return camera;
        } else {
            try {
                camera = Camera.open(0);
            } catch (Exception e) {
                return null;
            }
            return camera;
        }
    }

    /**
     * 开始预览相机
     *
     * @param holder
     */
    public static void startCamera(SurfaceHolder holder) {
        try {
            if (camera == null) {
                return;
            }
            camera.setPreviewDisplay(holder);
            camera.startPreview();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 停止相机
     */
    public static void stopCamera() {
        if (camera == null) {
            return;
        } else {
            // 更改时停止预览
            try {
                camera.stopPreview();
                camera.setPreviewCallback(null);
                camera.lock();
                camera.release();
                camera = null;
            } catch (Exception e) {
                // 忽略：试图停止不存在的预览
            }
            // 在此进行缩放、旋转和重新组织格式
            // 以新的设置启动预
        }
    }

    private static boolean checkCameraFacing(final int facing) {
        if (getSdkVersion() < Build.VERSION_CODES.GINGERBREAD) {
            return false;
        }
        final int cameraCount = Camera.getNumberOfCameras();
        Camera.CameraInfo info = new Camera.CameraInfo();
        for (int i = 0; i < cameraCount; i++) {
            try {

                Camera.getCameraInfo(i, info);
            } catch (Exception e) {

            }
            if (facing == info.facing) {
                return true;
            }
        }
        return false;
    }

    /**
     * 检查设备是否有摄像头
     *
     * @return
     */
    public static boolean hasCamera() {
        return hasBackFacingCamera() || hasFrontFacingCamera();
    }

    /**
     * 检查设备是否有后置摄像头
     *
     * @return
     */
    public static boolean hasBackFacingCamera() {
        final int CAMERA_FACING_BACK = 0;
        return checkCameraFacing(CAMERA_FACING_BACK);
    }

    /**
     * 检查设备是否有前置摄像头
     *
     * @return
     */
    public static boolean hasFrontFacingCamera() {
        final int CAMERA_FACING_BACK = 1;
        return checkCameraFacing(CAMERA_FACING_BACK);
    }

    public static int getSdkVersion() {
        return Build.VERSION.SDK_INT;
    }

    public static int getNumber() {
        return Camera.getNumberOfCameras();
    }

}
